package com.shiwaixiangcun.customer.module.homeservice

import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.View
import com.google.gson.reflect.TypeToken
import com.jaeger.recyclerviewdivider.RecyclerViewDivider
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import com.shiwaixiangcun.customer.ConfigSps
import com.shiwaixiangcun.customer.GlobalApi
import com.shiwaixiangcun.customer.GlobalConfig
import com.shiwaixiangcun.customer.R
import com.shiwaixiangcun.customer.base.BaseActivity
import com.shiwaixiangcun.customer.entity.CommonObjCallBack
import com.shiwaixiangcun.customer.network.ResponseConfig
import com.shiwaixiangcun.customer.network.StringDialogCallBack
import com.shiwaixiangcun.customer.utils.AppSharePreferenceMgr
import com.shiwaixiangcun.customer.utils.JsonUtil
import com.shiwaixiangcun.customer.widget.CustomLoadMoreView
import kotlinx.android.synthetic.main.activity_category_list.*
import kotlinx.android.synthetic.main.top_bar_white.*

/**
 * 服务列表

 */
class CategoryListActivity : BaseActivity() {


    var mTypeList: ArrayList<TypeListData>? = null
    var mAdapterType: AdapterServiceType? = null
    private var titleName: String? = null

    var siteId: Int = 20
    private var pageStart: Int = 1
    var pageSize: Int = 15
    var type: Long? = null
    var strToken: String? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_category_list)

        strToken = AppSharePreferenceMgr.get(mContext, ConfigSps.CURRENT_TOKEN, "") as String
        siteId = AppSharePreferenceMgr.get(mContext, ConfigSps.CURRENT_SITE_ID, 20) as Int
        pageStart = GlobalConfig.first_page
        pageSize = GlobalConfig.page_size

        iniBundleData()
        initView()

        initData(true)
    }


    private fun iniBundleData() {
        type = intent.extras.getLong("type")
        titleName = intent.extras.getString("name")


    }


    /**
     * 请求数据
     */
    private fun initData(isLoadMore: Boolean) {
        type?.let {
            OkGo.get<String>(GlobalApi.serviceTypeList)
                    .params("typeId", it)
                    .params("page.pn", pageStart)
                    .params("page.size", pageSize)
                    .params("fields", "id,feature,imagePath,price,serviceName,totalAmount")
                    .execute(object : StringDialogCallBack(this) {
                        override fun onError(response: Response<String>?) {
                            super.onError(response)
                            Log.e(BUG_TAG, "error")
                            mAdapterType?.setEnableLoadMore(true)
                            mAdapterType?.loadMoreFail()
                            refreshLayout.finishRefresh()
                        }

                        override fun onSuccess(response: Response<String>?) {
                            val type = object : TypeToken<CommonObjCallBack<TypeList>>() {}.type

                            val responseData = JsonUtil.fromJson<CommonObjCallBack<TypeList>>(response?.body(), type)

                            when (responseData.responseCode) {
                                ResponseConfig.SUCCESS -> {


                                    val size = responseData.data.elements.size
                                    if (isLoadMore) {
                                        if (size > 0) {
                                            mTypeList?.addAll(responseData.data.elements)
                                            mAdapterType?.notifyDataSetChanged()
                                        }
                                        if (size == 0 || size < pageSize) {
                                            mAdapterType?.loadMoreEnd(false)
                                        } else {
                                            mAdapterType?.loadMoreComplete()
                                        }
                                    } else {
                                        refreshLayout.finishRefresh()
                                        mAdapterType?.setEnableLoadMore(true)
                                        if (size == 0) {
                                            clayout_nodata.visibility = View.VISIBLE
                                        } else {
                                            mTypeList?.clear()
                                            mTypeList?.addAll(responseData.data.elements)
                                            mAdapterType?.notifyDataSetChanged()
                                        }
                                    }
                                }


                            }

                        }
                    })
        }
    }

    /**
     * 初始化试图
     */
    private fun initView() {


        tv_page_name.text = titleName

        back_left.setOnClickListener { finish() }
        mTypeList = ArrayList()
        mAdapterType = AdapterServiceType(mTypeList)

        rv_service_list.layoutManager = LinearLayoutManager(this)
        rv_service_list.adapter = mAdapterType
        val divider = RecyclerViewDivider.Builder(mContext)
                .setOrientation(RecyclerViewDivider.VERTICAL)
                .setStyle(RecyclerViewDivider.Style.BETWEEN)
                .setMarginLeft(20f)
                .setMarginRight(20f)
                .setSize(0.5f)
                .setEndSkipCount(1)
                .setColorRes(R.color.color_divider_0_1)
                .build()
        rv_service_list.addItemDecoration(divider)
        mAdapterType?.setOnItemClickListener { adapter, view, position ->
            val item = adapter.data[position] as TypeListData
//            val item = adapter.data[position] as ServiceData
            val bundle = Bundle()
            bundle.putLong("serviceId", item.id)
            readyGo(ServiceDetailActivity::class.java, bundle)
        }


        mAdapterType?.setLoadMoreView(CustomLoadMoreView())
        mAdapterType?.setOnLoadMoreListener({
            pageStart += 1
            refreshLayout.finishRefresh()
            initData(true)
        }, rv_service_list)

        refreshLayout.setOnClickListener {
            pageStart = 1
            mAdapterType?.setEnableLoadMore(false)
            initData(false)
        }


    }


}




